<?php
namespace app\admin\model;

use app\model\CommonModel;
use think\facade\Db;
use think\model\concern\SoftDelete;

class RsCate extends CommonModel
{
    use SoftDelete;

    public function cateList($params)
    {
        $where = $this->setWhere($params);
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = self::where($where)
            ->order('sort desc, id desc')
            ->paginate($paginate)
            ->toArray();

        return success('操作成功', $list);
    }

    /**
     * 商品分类，不分页
     */
    public function showCate()
    {
        $list = self::field('id, cate_name')
            ->order('sort desc, id desc')
            ->whereNull('deleted_at')
            ->select()
            ->toArray();
        return success('操作成功', $list);
    }

    //设置条件
    public function setWhere($params)
    {
        $where = [];
        return $where;
    }

    /**
     * 删除分类
     * */
    public function delCate($params)
    {
        $result=self::destroy($params['id']);
        return success('删除成功');
    }

    /**
     *  新增修改分类
     */
    public function optionCate($params)
    {
        $exits = self::where('id', '<>', $params['id'])
            ->where('cate_name', $params['cate_name'])
            ->find();
        if ($exits) {
            return fail('分类名称已经存在');
        }

        $info=self::where("id", $params['id'])->find();
        if (empty($info)) {
            $info=new self();
        }
        $info->cate_name=$params['cate_name'];
        $info->sort=$params['sort'];
        $info->status=$params['status'];
        $info->save();
        return success('保存成功！');
    }

    /**
     *  修改状态
     */
    public function optionStatus($params)
    {
        $info=self::where("id", $params['id'])->find();
        if (empty($params['id'])) {
            return fail('该分类不存在');
        }
        $info->status=$params['status'];
        $info->save();
        return success('保存成功！');
    }

    /**
     * 导入分类
     */
    public static function importCate($cateName)
    {
        $id=self::where("cate_name", $cateName)->value("id");
        if (empty($id)) {
            $cate=new self();
            $cate->cate_name=$cateName;
            $cate->save();
            $id=$cate->id;
        }
        return $id;
    }
    /**
     *   关联品牌
     */
    public function brand()
    {
        return $this->hasMany(RsBrand::class, 'cate_id');
    }
}
